package com.study.mythread.juc.producer;

import java.util.concurrent.TimeUnit;

/**
 * @program: java-study-of-learner
 * @description: 生产者‘和消费者
 * @author: future
 * @create: 2021-01-16 20:30
 **/
public class MyTestV1  {


    private int num = 1;
    private String name;
    public MyTestV1(String name) {
        this.name = name;
    }



    public synchronized void producer() throws InterruptedException {
        if(num!=0){
            this.wait();
        }
        num ++;
        System.out.println(this.name +"=======A======= 现在 num "+num);
        this.notifyAll();
    }
    public synchronized void consumer() throws InterruptedException {
        if(num==0){
            this.wait();
        }
        num--;
        System.out.println(this.name +"=======B======= 现在 num "+num);
        this.notifyAll();
    }

    public static void main(String[] args) {
        MyTestV1 testV1 = new MyTestV1("A");

        Thread t1 = new Thread(()->{
            for (int i = 0; i <20 ; i++) {
                try {
                    testV1.consumer();
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(()->{
            for (int i = 0; i <20 ; i++) {
                try {
                    testV1.producer();
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.start();
    }
}
